<template>
  <el-tree ref="tree" :default-expand-all="true" :check-strictly="false" :data="menuData" :props="menuProps" show-checkbox node-key="id" highlight-current @check-change="getCheckedArr" />
</template>

<script>
import { getMenuAuthority, modifyMenuAuthority } from '@/api/base/group'
import { fetchTree } from '@/api/base/menu'
import { addLevel } from '@/utils'

export default {
  name: 'GroupAuthority',
  props: {
    groupId: {
      type: String,
      required: true,
      default: '-1'
    }
  },
  data() {
    return {
      menuData: [],
      menuProps: {
        value: 'id',
        label: 'title',
        children: 'children'
      },
      temp: {},
      checkedArr: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取树的列表数据
    async getList() {
      try {
        const data = await fetchTree()
        addLevel(data)
        this.menuData = data
      } catch (error) {
        console.log(error)
      }
    },
    // 获取权限，设置勾选节点
    async getAuthority() {
      try {
        const { data } = await getMenuAuthority(this.groupId)
        for (const item of data) {
          // tree check-strictly=false时
          this.$refs.tree.setChecked(item.id, true)
        }
        // const checkedKeys = data.map(v => { // tree check-strictly=true时
        //   v = v.id
        //   return v
        // })
        // this.$refs.tree.setCheckedKeys(checkedKeys)
      } catch (error) {
        console.log(error)
      }
    },
    // 监听复选框被点击 获取选中项
    getCheckedArr() {
      // tree check-strictly=true时
      const parentArr = this.$refs.tree.getHalfCheckedKeys()
      const childArr = this.$refs.tree.getCheckedKeys()
      this.checkedArr = parentArr.concat(childArr)
      // this.checkedArr = this.$refs.tree.getCheckedKeys() // tree check-strictly=false时
    },
    // 获取已勾选节点，保存权限
    async updateAuthority() {
      const checkedStr = this.checkedArr.join(',')
      const { message } = await modifyMenuAuthority(this.groupId, { menuTrees: checkedStr })
      this.$message({
        message: message,
        type: 'success'
      })
    },
    // 对话框关闭时清空勾选项
    resetTree() {
      this.$refs.tree.setCheckedKeys([])
      this.checkedArr = []
    }
  }
}
</script>
